package com.anfeng.cms.util.time;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 吴朋
 * @date 2019/7/16
 */
public class WorkAgeUtil {

    /**
     * 根据入职时间和离职时间计算工龄
     * @param hireDate 入职时间
     * @param leaveDate 离职时间
     * @return 工龄
     */
    public static int getWorkAgeLength(Date hireDate, Date leaveDate) {
        // 如果入职时间为null  直接返回0
        if (null == hireDate) {
            return 0;
        }
        // 如果还未离职 就按照当前时间计算
        if (null == leaveDate) {
            leaveDate = new Date();
        }
        if (hireDate.after(leaveDate)) {
            return 0;
        }
        Calendar from = Calendar.getInstance();
        from.setTime(hireDate);

        Calendar to = Calendar.getInstance();
        to.setTime(leaveDate);

        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int fromDay = from.get(Calendar.DAY_OF_MONTH);

        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int toDay = to.get(Calendar.DAY_OF_MONTH);
        int workAge = 0;
        int yearDur = toYear - fromYear;
        int monthDur = toMonth - fromMonth;
        int dayDur = toDay - fromDay;

        if (yearDur == 0) {
            return workAge;
        }
        // 超过一年
        if (monthDur < 0) {
            workAge = yearDur - 1;
            return workAge;
        } else if (monthDur == 0) {
            if (dayDur < 0) {
                workAge = yearDur - 1;
                return workAge;
            }
        }

        return yearDur;
    }
}
